<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" showFooter :title="getTitle" width="50%" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts">
import { defineComponent, ref, computed, unref } from 'vue';
import { BasicForm, useForm } from '/@/components/Form/index';
import { formSchema } from './index-option';
import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
import { getMenuListApi, saveMenuApi, updateMenuApi } from '/@/api/sys/menu';
import { useMessage } from '/@/hooks/web/useMessage';

export default defineComponent({
  name: 'MenuDrawer',
  components: { BasicDrawer, BasicForm },
  emits: ['success', 'register'],
  setup(_, { emit }) {
    const isUpdate = ref(true);
    const menuId = ref();
    const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
      labelWidth: 80,
      schemas: formSchema,
      showActionButtonGroup: false,
      baseColProps: { lg: 12, md: 24 },
    });
    const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
      resetFields();
      setDrawerProps({ confirmLoading: false });
      isUpdate.value = !!data?.isUpdate;
      if (unref(isUpdate)) {
        menuId.value = data.record.menuId;
        setFieldsValue({
          ...data.record,
        });
      }
      const res = await getMenuListApi();
      const menus = res.data;
      updateSchema({
        field: 'parentId',
        componentProps: { treeData: menus },
      });
    });
    const getTitle = computed(() => (!unref(isUpdate) ? '新增菜单' : '编辑菜单'));

    const { createMessage } = useMessage();
    async function handleSubmit() {
      try {
        const values = await validate();
        setDrawerProps({ confirmLoading: true });
        let res;
        if (unref(isUpdate)) {
          const param = { ...values, menuId: menuId.value };
          res = await updateMenuApi(param);
        } else {
          res = await saveMenuApi(values);
        }
        createMessage.success(res.msg);
        closeDrawer();
        emit('success');
      } finally {
        setDrawerProps({ confirmLoading: false });
      }
    }
    return { registerDrawer, registerForm, getTitle, handleSubmit };
  },
});
</script>
